<script setup lang="ts">
import { ref } from 'vue';

import {
  CommentOutlined,
  LikeOutlined,
  PlusOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { marked } from 'marked';

const storyModalVisible = ref(false);
const showStoryModal = ref(false);
const selectedStory = ref<any>(null);
const newComment = ref('');
const newStory = ref({
  title: '',
  type: 'single',
  chapter: 1,
  content: '',
});

const stories = ref([
  {
    id: 's-1',
    title: '太祖创业记',
    excerpt: '讲述朱元璋从贫农到开国皇帝的传奇经历...',
    content: `# 太祖创业记

## 第一章：苦难童年

至正四年（1344年），濠州钟离发生大旱...

朱元璋幼年丧父母，孤苦无依...`,
    author: '朱标',
    authorAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuBiao',
    createTime: '1390-05-10T10:00:00Z',
    likes: 1234,
    comments: 89,
    isSerial: true,
    chapter: 1,
    onChain: true,
    liked: false,
  },
  {
    id: 's-2',
    title: '靖难之役亲历记',
    excerpt: '朱棣亲述靖难之役的前因后果...',
    content: `# 靖难之役亲历记

建文元年，朝廷削藩...`,
    author: '朱高炽',
    authorAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuGaochi',
    createTime: '1405-03-15T10:00:00Z',
    likes: 892,
    comments: 56,
    isSerial: false,
    onChain: true,
    liked: false,
  },
]);

const storyComments = ref([
  {
    id: 1,
    userName: '朱瞻基',
    userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuZhanji',
    content: '太祖功德，永垂不朽！',
    time: '2025-01-10T14:00:00Z',
  },
]);

function renderMarkdown(text: string) {
  return marked(text);
}

function formatTime(time: string) {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
}

function viewStory(story: any) {
  selectedStory.value = story;
  storyModalVisible.value = true;
}

function likeStory(story: any) {
  story.liked = !story.liked;
  story.likes += story.liked ? 1 : -1;
  message.success(story.liked ? '点赞成功！' : '取消点赞');
}

function submitComment() {
  if (!newComment.value.trim()) {
    message.warning('请输入评论内容');
    return;
  }
  message.loading('正在上链...', 2);
  setTimeout(() => {
    message.success('评论已提交并上链！');
    newComment.value = '';
  }, 2000);
}

function submitStory() {
  message.success('故事投稿成功！审核通过后将发布（Mock模式）');
  showStoryModal.value = false;
}
</script>

<template>
  <div class="stories-page">
    <a-card>
      <template #title>
        <div class="page-header">
          <span>📖 家族故事</span>
          <a-button type="primary" @click="showStoryModal = true">
            <PlusOutlined /> 投稿故事
          </a-button>
        </div>
      </template>

      <a-list :data-source="stories" :pagination="{ pageSize: 5 }">
        <template #renderItem="{ item }">
          <a-list-item>
            <template #actions>
              <a-space>
                <span> <LikeOutlined /> {{ item.likes }} </span>
                <span> <CommentOutlined /> {{ item.comments }} </span>
              </a-space>
            </template>
            <a-list-item-meta @click="viewStory(item)" style="cursor: pointer">
              <template #avatar>
                <a-avatar :src="item.authorAvatar" size="large" />
              </template>
              <template #title>
                <a-space>
                  <span>{{ item.title }}</span>
                  <a-tag v-if="item.isSerial" color="purple">连载中</a-tag>
                  <a-tag v-if="item.onChain" color="green">已上链</a-tag>
                </a-space>
              </template>
              <template #description>
                <div class="story-preview">
                  {{ item.excerpt }}
                </div>
                <div class="story-meta">
                  作者：{{ item.author }} · {{ formatTime(item.createTime) }}
                  <a-tag v-if="item.chapter" size="small">
                    第{{ item.chapter }}章
                  </a-tag>
                </div>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-card>

    <!-- 故事详情Modal -->
    <a-modal
      v-model:open="storyModalVisible"
      :title="selectedStory?.title"
      width="900px"
      :footer="null"
    >
      <div v-if="selectedStory" class="story-detail">
        <div class="story-header">
          <a-avatar :src="selectedStory.authorAvatar" size="large" />
          <div class="author-info">
            <h4>{{ selectedStory.author }}</h4>
            <p>{{ formatTime(selectedStory.createTime) }}</p>
          </div>
          <a-space>
            <a-button @click="likeStory(selectedStory)">
              <LikeOutlined
                :style="{ color: selectedStory.liked ? '#ff4d4f' : undefined }"
              />
              {{ selectedStory.likes }}
            </a-button>
            <a-button> <ShareAltOutlined /> 分享 </a-button>
          </a-space>
        </div>

        <a-divider />

        <div
          class="story-content"
          v-html="renderMarkdown(selectedStory.content)"
        ></div>

        <a-divider />

        <div class="comments-section">
          <h4>评论区 ({{ selectedStory.comments }})</h4>
          <a-list :data-source="storyComments" size="small">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :src="item.userAvatar" />
                  </template>
                  <template #title>{{ item.userName }}</template>
                  <template #description>{{ item.content }}</template>
                </a-list-item-meta>
                <div>{{ formatTime(item.time) }}</div>
              </a-list-item>
            </template>
          </a-list>

          <a-textarea
            v-model:value="newComment"
            :rows="2"
            placeholder="写下您的评论..."
            style="margin-top: 16px"
          />
          <a-button
            type="primary"
            @click="submitComment"
            style="margin-top: 8px"
          >
            提交评论（上链）
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 投稿故事Modal -->
    <a-modal
      v-model:open="showStoryModal"
      title="投稿家族故事"
      @ok="submitStory"
      width="800px"
    >
      <a-form layout="vertical">
        <a-form-item label="故事标题">
          <a-input v-model:value="newStory.title" placeholder="输入故事标题" />
        </a-form-item>
        <a-form-item label="故事类型">
          <a-radio-group v-model:value="newStory.type">
            <a-radio value="single">单篇</a-radio>
            <a-radio value="serial">连载</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="newStory.type === 'serial'" label="章节">
          <a-input-number v-model:value="newStory.chapter" :min="1" />
        </a-form-item>
        <a-form-item label="故事内容（支持Markdown）">
          <a-textarea v-model:value="newStory.content" :rows="15" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.stories-page {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .story-preview {
    margin-bottom: 8px;
    color: #666;
  }

  .story-meta {
    font-size: 12px;
    color: #999;
  }

  .story-detail {
    .story-header {
      display: flex;
      gap: 16px;
      align-items: center;

      .author-info {
        flex: 1;

        h4 {
          margin: 0;
        }

        p {
          margin: 0;
          font-size: 12px;
          color: #999;
        }
      }
    }

    .story-content {
      font-size: 15px;
      line-height: 1.8;

      h1,
      h2,
      h3 {
        margin-top: 24px;
        margin-bottom: 12px;
      }

      p {
        margin-bottom: 16px;
      }
    }

    .comments-section {
      h4 {
        margin-bottom: 16px;
      }
    }
  }
}
</style>
